#!/usr/bin/env bash
# Copyright 2025 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__() {
  cat <<EOF
configVersion: v1
kubernetesCustomResourceConversion:
  - name: v1alpha1_to_v1alpha2
    crdName: clusterloggingconfigs.deckhouse.io
    conversions:
      - fromVersion: deckhouse.io/v1alpha1
        toVersion: deckhouse.io/v1alpha2

  - name: v1alpha2_to_v1alpha1
    crdName: clusterloggingconfigs.deckhouse.io
    conversions:
      - fromVersion: deckhouse.io/v1alpha2
        toVersion: deckhouse.io/v1alpha1
EOF
}

function __on_conversion::v1alpha1_to_v1alpha2() {
  if converted=$(context::jq -r '.review.request.objects // [] | map(
    if .apiVersion == "deckhouse.io/v1alpha1" then
      .apiVersion = "deckhouse.io/v1alpha2" |
      if .spec.kubernetesPods.namespaceSelector and (.spec.kubernetesPods.namespaceSelector.labelSelector | not) then
        .spec.kubernetesPods.namespaceSelector.labelSelector = (
          if .spec.kubernetesPods.namespaceSelector.matchNames then
            { "matchExpressions": [{ "key": "kubernetes.io/metadata.name", "operator": "In", "values": .spec.kubernetesPods.namespaceSelector.matchNames }] }
          elif .spec.kubernetesPods.namespaceSelector.excludeNames then
            { "matchExpressions": [{ "key": "kubernetes.io/metadata.name", "operator": "NotIn", "values": .spec.kubernetesPods.namespaceSelector.excludeNames }] }
          else
            null
          end
        ) |
        del(.spec.kubernetesPods.namespaceSelector.matchNames, .spec.kubernetesPods.namespaceSelector.excludeNames)
      else . end
    else . end
  )'); then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of clusterloggingconfigs.deckhouse.io from v1alpha1 to v1alpha2 failed"}
EOF
  fi
}

function __on_conversion::v1alpha2_to_v1alpha1() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
    if .apiVersion == "deckhouse.io/v1alpha2" then
      .apiVersion = "deckhouse.io/v1alpha1"
    else . end
  )'); then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of grafanaadditionaldatasources.deckhouse.io failedfrom v1alpha2 to v1alpha1 failed"}
EOF
  fi
}
hook::run "$@"
